/**
 * node 当前文件，打开index.html 点击第一个按钮下载导出的Excel
*/


const express = require('express');
const nodeExcel = require('excel-export');
const app = express();
const superagent = require('superagent');
const cheerio = require('cheerio');
const reptileUrl = "https://movie.douban.com/chart";
const request = require('request');

//设置跨域访问 ---> 这里必须设置
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1');
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});


let data = [],releaseTime = [],actors = [],confRowsData = [];
/**
 * node运行即执行抓取数据，可根据项目需求调整
 */
(function aliasfun(){
  console.log(2222)
  request(reptileUrl, function (error, response, body) {
    // console.log(body)
    if (!error && response.statusCode == 200) {
      let $ = cheerio.load(body); //当前的$符相当于拿到了所有的body里面的选择器
      $(".indent table .item .pl2 .pl").each(function(i, elem){
        if(i % 2 == 1) return;
        /**
         * 演员变量，上映时间，演员
         * */ 
        let _actorInfo = elem.children[0].data.split(' / '),
            _setInfo = [], // Excel配置 目前：上映时间，演员，时长
            _releaseTime = [],
            _actors = [],
            _longTime = [];
        _actorInfo.forEach(function(item){
          /**
           * 正则匹配判断，区分演员和上映时间
           */
          if(item.match(RegExp("-")) && item.match(RegExp("20"))) {
            _releaseTime.push(item)
          }else if(item.match(RegExp("分钟"))){
            _longTime.push(item)
          }else {
            _actors.push(item)
          }  
        })

        _setInfo.push(_releaseTime.join(','),_actors.join(','),_longTime.join(','));

        confRowsData.push(_setInfo);
        data.push(_actorInfo);
        releaseTime.push(_releaseTime.join(','))
        actors.push(_actors.join(','))
      })
    } else {
      console.log("抓取失败")
    }
  })
})()

/**
 * 调试接口
*/
app.get('/getDouBan', function(req, res){
  request(reptileUrl, function (error, response, body) {
    let data = [],releaseTime = [],actors = [];
    if (!error && response.statusCode == 200) {
      // console.log(body)
      //返回的body为抓到的网页的html内容
      let $ = cheerio.load(body); //当前的$符相当于拿到了所有的body里面的选择器
      // var navText=$(".indent table .item .pl2"); //拿到导航栏的内容
      // console.log($(".indent table .item .pl2 .pl"))
      $(".indent table .item .pl2 .pl").each(function(i, elem){
        // console.log(elem.children[0].data)
        if(i % 2 == 1) return;
        // 演员变量
        let _actorInfo = elem.children[0].data.split(' / '),
            _releaseTime = [],
            _actors = [];
        _actorInfo.forEach(function(item){
          if(item.match(RegExp("-")) && item.match(RegExp("20"))) {
            _releaseTime.push(item)

          }else {
            _actors.push(item)
          }
        })
        data.push(_actorInfo)
        releaseTime.push(_releaseTime.join(','))
        actors.push(_actors.join(','))
      })
      res.setHeader('Content-Type', 'application/vnd.openxmlformats');
      res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
      res.send(releaseTime);
    }
  })
});

/**
 * 导出Excel接口
*/
app.get('/Excel', function(req, res){
    let conf ={};
    // console.log(confRowsData)
    conf.stylesXmlFile = "styles.xml";
    /**
     * 写入Excel数据配置 cols rows
    */
    conf.cols = [{
        caption:'上映时间',
        type:'string'
    },{
        caption:'演员',
        type:'string'
    },{
        caption:'时长',
        type:'string'
    }];
    conf.rows = confRowsData;
    const result = nodeExcel.execute(conf);
    res.setHeader('Content-Type', 'application/vnd.openxmlformats');
    res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
    res.end(result, 'binary');
});

app.listen(3000);
console.log('Listening on port 3000');